package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chuanglan.SMSConst;
import com.chuanglan.sms.util.ChuangLanSmsUtil;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.CodeRecord;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetSystemConfig;
import com.ruoyi.system.domain.HatchetSystemDepartment;
import com.ruoyi.system.domain.HatchetSystemUser;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.HatchetAgentMapper;
import com.ruoyi.system.mapper.HatchetSystemDepartmentMapper;
import com.ruoyi.system.service.ICodeRecordService;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetMerchantService;
import com.ruoyi.system.service.IHatchetSystemUserService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.vo.AgentMerchantChangeVo;
import com.ruoyi.system.vo.SecurityUtils;

/**
 * 代理商 服务层实现
 * 
 * @author xj
 * @date 2019-02-15
 */
@Service
public class HatchetAgentServiceImpl implements IHatchetAgentService {
	@Autowired
	private HatchetAgentMapper hatchetAgentMapper;
	@Autowired
	private HatchetSystemDepartmentMapper departmentMapper;
	@Autowired
	private IHatchetSystemUserService hatchetSystemUserService;
	@Autowired
	private IHatchetAgentService hatchetAgentService;
	@Autowired
	private ISysUserService userService;
	@Autowired
	private IHatchetMerchantService hatchetMerchantService;
	@Autowired
	private ICodeRecordService codeRecordService;

	/**
	 * 查询代理商信息
	 * 
	 * @param iD
	 *            代理商ID
	 * @return 代理商信息
	 */
	@Override
	public HatchetAgent selectHatchetAgentById(String iD) {
		return hatchetAgentMapper.selectHatchetAgentById(iD);
	}

	/**
	 * 查询代理商列表
	 * 
	 * @param hatchetAgent
	 *            代理商信息
	 * @return 代理商集合
	 */
	@Override
	public List<HatchetAgent> selectHatchetAgentList(HatchetAgent hatchetAgent) {
		return hatchetAgentMapper.selectHatchetAgentList(hatchetAgent);
	}

	/**
	 * 新增代理商
	 * 
	 * @param hatchetAgent
	 *            代理商信息
	 * @return 结果
	 */
	@Override
	public int insertHatchetAgent(HatchetAgent hatchetAgent) {
		return hatchetAgentMapper.insertHatchetAgent(hatchetAgent);
	}

	/**
	 * 修改代理商
	 * 
	 * @param hatchetAgent
	 *            代理商信息
	 * @return 结果
	 */
	@Override
	public int updateHatchetAgent(HatchetAgent hatchetAgent) {
		return hatchetAgentMapper.updateHatchetAgent(hatchetAgent);
	}

	/**
	 * 删除代理商对象
	 * 
	 * @param ids
	 *            需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteHatchetAgentByIds(String ids) {
		return hatchetAgentMapper.deleteHatchetAgentByIds(Convert.toStrArray(ids));
	}

	/**
	 * 根据agentNo 获取代理商信息
	 */
	@Override
	public HatchetAgent selectHatchetAgentByNo(String agentNo) {
		return hatchetAgentMapper.selectHatchetAgentByNo(agentNo);
	}

	@Override
	public List<HatchetAgent> selectHatchetAgentByaction(HatchetAgent hatchetAgent) {
		return hatchetAgentMapper.selectHatchetAgentByaction(hatchetAgent);
	}

	/**
	 * 查询树结构代理商
	 * 
	 * @param hatchetAgent
	 * @return
	 */
	public List<HatchetAgent> selectHatchetAgentTree(HatchetAgent hatchetAgent) {
		return hatchetAgentMapper.selectHatchetAgentTree(hatchetAgent);
	}

	/**
	 * 查询直接下属代理商财务信息
	 * 
	 * @param hatchetAgent
	 * @return
	 */
	public List<AgentMerchantChangeVo> selectUnderAgentMoneyForDLS(HatchetAgent hatchetAgent) {
		return hatchetAgentMapper.selectUnderAgentMoneyForDLS(hatchetAgent);
	}

	/**
	 * 通过父节点获取父节点下最大的Code
	 * 
	 * @param agent
	 * @return
	 */
	synchronized public String getCurLvlCode(HatchetAgent agent) {
		if (agent == null)
			throw new RuntimeException("需指定代理商");
		if (StringUtils.isEmpty(agent.getParentId()))
			agent.setParentId(null);
		// 获取最大编号
		String curMaxCode = hatchetAgentMapper.selectMaxCode(agent.getParentId());
		return dealCurCode(curMaxCode, agent.getParentId());
	}

	/**
	 * 处理编号
	 * 
	 * @param code
	 * @return
	 */
	private String dealCurCode(String code, String pId) {

		String max = null;
		String[] cuCode;

		if (StringUtils.isEmpty(code)) {
			if (StringUtils.isEmpty(pId))
				return "00010000000000000000000000000000";
			else {
				// 通过ParentID获取实体
				HatchetAgent agent = hatchetAgentMapper.selectHatchetAgentById(pId);
				if (agent == null)
					throw new RuntimeException("获取编号出错：无法获取parentId(" + pId + ")的实体");
				if (agent.getAgentCode() == null || "".equals(agent.getAgentCode()))
					throw new RuntimeException("获取编号出错：parentId(" + pId + ")的实体中 不存在Code");

				cuCode = split(agent.getAgentCode(), 5);

				for (int i = 0; i < cuCode.length; i++) {
					String s = cuCode[i];
					if ("0000".equals(s)) {
						int start = i * 4;
						max = agent.getAgentCode().substring(0, start) + "0001"
								+ agent.getAgentCode().substring(start + 4) + "0000";
						break;
					} else {
						max = agent.getAgentCode() + "0001";
					}
				}
				System.out.println("上级代理商的代理编号为" + agent.getAgentCode() + "++++++++++");

				if (max == null)
					throw new RuntimeException("获取编号出错：无法获取parentId(" + pId + ")下最大编号");
				else
					return max;
			}
		}

		cuCode = split(code, 5);
		for (int i = cuCode.length - 1; i > -1; i--) {
			String s = cuCode[i];
			if (!"0000".equals(s)) {
				int start = i * 4;
				max = code.substring(0, start) + codeAddOne(s) + code.substring(start + 4);
				break;
			}
		}

		return max;
	}

	/**
	 * 编号+1
	 * 
	 * @param code
	 * @return
	 */
	private String codeAddOne(String code) {
		return ((Integer.parseInt(code) + 10001) + "").substring(1);
	}

	/**
	 * 编号+1
	 * 
	 * @param code
	 * @return
	 */
	private String codeAddOne4Two(String code) {
		return ((Integer.parseInt(code) + 10001) + "").substring(1);
	}

	/**
	 * 将msg以 (num - 1)的长度分组
	 * 
	 * @param msg
	 * @param num
	 * @return
	 */
	public static String[] split(String msg, int num) {
		int len = msg.length();
		if (len <= num)
			return new String[] { msg };
		int count = len / (num - 1);
		count += len > (num - 1) * count ? 1 : 0; // 这里应该值得注意
		String[] result = new String[count];
		int pos = 0;
		int splitLen = num - 1;
		for (int i = 0; i < count; i++) {
			if (i == count - 1)
				splitLen = len - pos;
			result[i] = msg.substring(pos, pos + splitLen);
			pos += splitLen;
		}
		return result;
	}

	/**
	 * 截取代理商用户名
	 * 
	 * @param agent
	 * @return
	 */
	public synchronized String spiltAgentCodeNo(HatchetAgent agent) {
		String code = agent.getAgentCode(); // 0001 0000 0000 0000
		// 反转Code，并确定是多少级 00090000000000000000000000000000
		BigDecimal length = new BigDecimal(StringUtils.likeDepartmentCode(code).length());
		BigDecimal codeLevel = length.divide(new BigDecimal(4));
		codeLevel = codeLevel.setScale(0, BigDecimal.ROUND_UP);
		// 1级 --> 18 + 00000
		// 2级 --> 28 + 00000
		// 查询最大Code
		// String maxCode = "1800001";
		int first = codeLevel.intValue();
		// String maxCode = (String) selectDAO.object("SYSTEM.queryAgentLevelMax", first
		// + "8");
		String maxCode = hatchetAgentMapper.queryAgentLevelMax(first + "8");

		if (maxCode == null)
			return first + "800001";
		// 处理最大Code 并+1
		Integer maxCodeInt = Integer.parseInt(maxCode.substring(2)) + 1;
		return first + "8" + StringUtils.leftPad(maxCodeInt.toString(), 5, "0");
	}

	/***
	 * 通过代理商创建对应的组织机构
	 * 
	 * @param agent
	 */
	@Transactional
	public synchronized HatchetSystemDepartment insertSystemDeployMentByAgent(HatchetAgent agent) {
		// 如果是一级节点，则添加到 【代理商】 下面
		String code;
		if (agent.getParentId() == null || agent.getParentId().equals("")) {
			code = "00010002000000000000000000000000";
		} else { // 非一级节点，则通过Department_Code 确定上下级
			HatchetAgent parent = hatchetAgentMapper.selectHatchetAgentById(agent.getParentId());
			code = parent.getDepartmentCode();
		}
		System.out.println("我的上级代理码是" + code + "+++++++++");
		String maxCode = departmentMapper.queryDepartMentMaxCode(code);
		HatchetSystemDepartment department = new HatchetSystemDepartment();
		department.setID(StringUtils.randomUUID() + "");
		department.setUserId("1");
		department.setDepartmentName(agent.getAgentName());
		department.setCreateTime(new Date());
		department.setSTATUS("10A");

		HatchetSystemDepartment department2 = new HatchetSystemDepartment();
		department2.setDepartmentCode(code);
		List<HatchetSystemDepartment> parentDepartMent = departmentMapper
				.selectHatchetSystemDepartmentList(department2);
		department.setParentId(parentDepartMent.get(0).getID());
		System.out.println("代理商编号为" + code + "++++++++");

		// 编号的处理
		if (maxCode == null || "".equals(maxCode)) {
			// maxCode = "00010001000100000000000000000000";
			String[] cuCode = split(code, 5);
			System.out.println("截取后的数组是" + cuCode + "+++++++++");
			if (code.length() == 32) {
				for (int i = 0; i < cuCode.length; i++) {
					String s = cuCode[i];
					if ("0000".equals(s)) {
						int start = i * 4;
						maxCode = code.substring(0, start) + "0001" + code.substring(start + 4);
						break;
					} else {
						maxCode = code + "0001";
					}

				}
			} else {
				maxCode = code + "0001";
			}
		} else {
			String[] cuCode = split(maxCode, 5);
			for (int i = cuCode.length - 1; i > -1; i--) {
				String s = cuCode[i];
				if (!"0000".equals(s)) {
					int start = i * 4;
					maxCode = maxCode.substring(0, start) + codeAddOne4Two(s) + maxCode.substring(start + 4);
					break;
				}
			}
		}
		department.setDepartmentCode(maxCode);

		departmentMapper.insertHatchetSystemDepartment(department);
		return department;
	}

	/**
	 * 截取代理code看自己下级
	 * 
	 * @param code
	 * @return
	 */
	public String splitAgentCodeLower(String code) {
		String[] cuCode = split(code, 5);
		StringBuffer sb = new StringBuffer();
		Boolean b = true;
		for (int i = 0; i < cuCode.length; i++) {
			if ("0000".equals(cuCode[i]) && b) {
				sb.append("____");
				b = false;
			} else {
				sb.append(cuCode[i]);
			}
		}
		code = code.replaceFirst("[0]{4}", "____");
		return sb.toString();
	}

	/**
	 * 修改代理商禁用状态
	 * 
	 * @param agentId
	 *            代理商id
	 * @param logoText
	 *            禁用原因
	 * @return
	 */
	@Transactional
	public Map<String, Object> changeStatus(String agentId, String logoText) {
		Map<String, Object> map = new HashMap<>();
		HatchetAgent obAgent = selectHatchetAgentById(agentId);
		HatchetSystemUser user = hatchetSystemUserService.selectSystemUserByAgentNo(obAgent.getAgentNo());
		if ("10A".equals(obAgent.getEmployStatus())) {
			if (StringUtils.isEmpty(logoText)) {
				map.put("status", BusinessStatus.FAIL);
				map.put("msg", "禁用原因不能为空");
				return map;
			}
			obAgent.setEmployStatus("10B");
			obAgent.setLogoText(logoText);
			user.setSTATUS("10B");
			;
			user.setUpdateTime(new Date());
			int updateHatchetSystemUser = hatchetSystemUserService.updateHatchetSystemUser(user);
			if (updateHatchetSystemUser > 0) {
				int updateHatchetAgent = updateHatchetAgent(obAgent);
				if (updateHatchetAgent > 0) {
					map.put("status", BusinessStatus.SUCCESS);
					map.put("msg", "操作成功");
					return map;
				} else {
					throw new RuntimeException("操作失败请华稍后重试！");
				}
			} else {
				throw new RuntimeException("操作失败请华稍后重试！");
			}
		}
		if ("10B".equals(obAgent.getEmployStatus())) {
			obAgent.setEmployStatus("10A");
			user.setSTATUS("10A");
			;
			user.setUpdateTime(new Date());
			int updateHatchetSystemUser = hatchetSystemUserService.updateHatchetSystemUser(user);
			if (updateHatchetSystemUser > 0) {
				int updateHatchetAgent = updateHatchetAgent(obAgent);
				if (updateHatchetAgent > 0) {
					map.put("status", BusinessStatus.SUCCESS);
					map.put("msg", "操作成功");
					return map;
				} else {
					throw new RuntimeException("操作失败请华稍后重试！");
				}
			} else {
				throw new RuntimeException("操作失败请华稍后重试！");
			}
		}
		return null;
	}

	@Override
	@Transactional
	public Map<String, Object> addAgent(HatchetAgent hatchetAgent) {
		Map<String, Object> map = new HashMap<>();
		HatchetSystemConfig systemConfig = new HatchetSystemConfig();
		// 将法人姓名赋值给开户名
		hatchetAgent.setCreateUserId("F9946CAE0D574FB1BDFDAE922F7821E1");// 默认admin创建
		hatchetAgent.setAppIdentity("10A");
		hatchetAgent.setAccountName(hatchetAgent.getCorpName());
		if ("0".equals(hatchetAgent.getTYPE())) {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "请选择代理商等级！");
			return map;
		} else if ("1".equals(hatchetAgent.getTYPE())) {// 城市运营商
			systemConfig.setConfigCode("CODE10000001");
		} else if ("2".equals(hatchetAgent.getTYPE())) {// 城市商务中心
			systemConfig.setConfigCode("CODE10000002");
		} else if ("3".equals(hatchetAgent.getTYPE())) {// 联合创始人
			systemConfig.setConfigCode("CODE10000003");
		}
		if (StringUtils.isEmpty(hatchetAgent.getLEVEL())) {
			hatchetAgent.setLEVEL(null);
		}

		// 如果是高级合伙人获取上级联创的agentId
		if ("1".equals(hatchetAgent.getLEVEL())) {
			HatchetAgent agent = hatchetAgentService.selectHatchetAgentByNo(hatchetAgent.getAgentNo());
			if (agent != null) {
				hatchetAgent.setFreeStatus(agent.getID());
				hatchetAgent.setFastCount(0);
			}
		}

		// 查询上级代理码数
		HatchetAgent parentAgent = hatchetAgentService.selectHatchetAgentById(hatchetAgent.getParentId());
		if (parentAgent != null) {
			int parentT = Integer.parseInt(parentAgent.getTYPE());
			if (parentT <= Integer.parseInt(hatchetAgent.getTYPE())) {
				map.put("status", BusinessStatus.FAIL);
				map.put("msg", "新建的代理等级必须小于上级代理！");
				return map;
			}
		}
		if (hatchetAgent.getFastCount() == null) {
			hatchetAgent.setFastCount(0);
		} else {
			hatchetAgent.setFastCount(hatchetAgent.getFastCount());
		}
		hatchetAgentService.updateHatchetAgent(parentAgent);

		// 查到区域代码
		HatchetAgent agent = new HatchetAgent();
		agent.setAgentName(hatchetAgent.getAgentName());
		List<HatchetAgent> agentList = hatchetAgentService.selectHatchetAgentList(agent);

		try {
			if (agentList.size() == 0) {
				hatchetAgent.setID(StringUtils.randomUUID());
				hatchetAgent.setAgentCode(hatchetAgentService.getCurLvlCode(hatchetAgent));
				hatchetAgent.setAgentNo(hatchetAgentService.spiltAgentCodeNo(hatchetAgent));// 生成代理商编号
				hatchetAgent.setParentId(hatchetAgent.getParentId());
				hatchetAgent.setSTATUS("10B");// 默认状态为创建
				hatchetAgent.setEmployStatus("10A"); // 使用状态
				hatchetAgent.setADDRESS(hatchetAgent.getADDRESS());// 地址
				hatchetAgent.setAgentUserId(StringUtils.randomUUID());// 代理商编号
				hatchetAgent.setCreateTime(new Date());// 创建时间
				hatchetAgent.setOpenSecondLevel("10B"); // 默认不开启
				hatchetAgent.setTotalMoney(new BigDecimal(0));// 默认为0
				if (!StringUtils.isEmpty(hatchetAgent.getLogoText())) {
					if ("-".equals(hatchetAgent.getLogoText().trim())) {
						hatchetAgent.setLogoText("");
					}
				}

				// ------------------添加代理商code------------------------
				HatchetSystemDepartment sdt = hatchetAgentService.insertSystemDeployMentByAgent(hatchetAgent);
				hatchetAgent.setDepartmentCode(sdt.getDepartmentCode());

			}
			String s = hatchetAgent.getIdCardNo();
			String passWord = s.substring(s.length() - 8, s.length());
			hatchetAgentService.insertHatchetAgent(hatchetAgent);// 保存代理商信息

			// 添加新系统登陆用户信息
			SysUser user1 = new SysUser();
			user1.setLoginName(hatchetAgent.getAgentNo());
			user1.setUserName(hatchetAgent.getAgentName());
			user1.setPhonenumber(hatchetAgent.getCorpPhone());

			user1.setPassword(SecurityUtils.EncoderByMd5(passWord));
			user1.setCreateBy("admin");
			userService.insertUser(user1);

			// 发短信给代理商账号密码
			String agentLevel = "";
			if ("1".equals(hatchetAgent.getTYPE())) {
				agentLevel = "运营商管理后台";
			} else if ("2".equals(hatchetAgent.getTYPE())) {
				agentLevel = "城市商务中心管理后台";
			} else if ("3".equals(hatchetAgent.getTYPE())) {
				agentLevel = "高级合伙人管理后台";
			}
			String params = String.format(hatchetAgent.getCorpPhone(), hatchetAgent.getCorpName(), agentLevel,
					hatchetAgent.getAgentNo());
			ChuangLanSmsUtil.sendSMSVar(SMSConst.success_to_agent, params);

			if (hatchetAgent.getCorpPhone() != null) {
				String phone = hatchetAgent.getCorpPhone();
				HatchetMerchant hm = hatchetMerchantService.getMerchantByPhoneOrLinkPhone(phone, "KSD");
				if (hm != null) {
					hm.setAgentId(hatchetAgent.getID());
					hm.setDepartmentCode(hatchetAgent.getDepartmentCode());
					hatchetMerchantService.updateHatchetMerchant(hm);
				}
			}
			// 创建加码和扣码记录
			map.put("status", BusinessStatus.SUCCESS);
			map.put("msg", "添加成功!");
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "操作异常");
			return map;
		}

	}

	/**
	 * 创建加码减码记录
	 * 
	 * @param hatchetMerchant
	 * @param agent
	 * @param codeCount
	 * @return
	 */
	@Transactional
	public boolean creatCodeRecord(HatchetAgent parentAgent, HatchetAgent agent, int codeCount) {
		// 添加加码和减码记录
		String fromId = StringUtils.randomUUID();
		String toId = StringUtils.randomUUID();
		// 创建升级码加码记录
		CodeRecord codeRecord1 = new CodeRecord();
		codeRecord1.setId(toId);
		codeRecord1.setAgentId(agent.getID());
		codeRecord1.setName(agent.getAgentName());
		codeRecord1.setCount(codeCount);
		codeRecord1.setType("0");
		codeRecord1.setFromId(fromId);
		// 操作前升级码数量
		codeRecord1.setField1(agent.getFastCount() + "");
		// 操作后升级码数量
		codeRecord1.setField2((agent.getFastCount() + codeCount) + "");
		codeRecord1.setCreateTime(new Date());
		int insertCodeRecord1 = codeRecordService.insertCodeRecord(codeRecord1);
		if (insertCodeRecord1 > 0) {
			// 创建减码记录
			CodeRecord codeRecord2 = new CodeRecord();
			codeRecord2.setId(fromId);
			codeRecord2.setAgentId(parentAgent.getID());
			codeRecord2.setName(parentAgent.getAgentName());
			codeRecord2.setCount(codeCount);
			codeRecord2.setType("1");
			codeRecord2.setToId(toId);
			// 操作前升级码数量
			codeRecord2.setField1((parentAgent.getFastCount() - codeCount) + "");
			// 操作后升级码数量
			codeRecord2.setField2(parentAgent.getFastCount() + "");
			codeRecord2.setCreateTime(new Date());
			int insertcodeRecord2 = codeRecordService.insertCodeRecord(codeRecord2);
			if (insertcodeRecord2 > 0) {
				return true;
			} else {
				throw new RuntimeException("创建升级码减码记录失败");
			}
		} else {
			throw new RuntimeException("创建升级码加码记录失败");
		}
	}

	@Override
	public List<HatchetAgent> selectAllAgent() {
		return hatchetAgentMapper.selectAllAgent();
	}

}
